package com.suning.sawp.in.controller;

import java.io.IOException;
import java.io.InputStream;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import com.suning.framework.image.service.ImageServiceException;
import com.suning.sawp.constants.ErrorCodeConstants;
import com.suning.sawp.constants.LoggerConstants;
import com.suning.sawp.dto.common.RecordList;
import com.suning.sawp.po.contend.CommPersonDTO;
import com.suning.sawp.po.contend.PersonBean;
import com.suning.sawp.po.contend.TopicBean;
import com.suning.sawp.service.impl.contend.ContendService;
import com.suning.sawp.service.impl.contend.UIMGStore;
import com.suning.sawp.service.util.BaseContants;

/**
 * 〈主推任务后台控制类〉<br>
 * 〈功能详细描述〉
 *
 * @author 12061748
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
@RequestMapping("/adminPage/contend")
public class ContendBackController extends DjBaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerConstants.SAWP_SERVICE);

    @Autowired
    ContendService contendService;

    @Autowired
    UIMGStore uimgStore;

    /**
     * 
     * 功能描述:查询话题列表 <br>
     * 〈功能详细描述〉
     *
     * @param start
     * @param limit
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/queryTopic.do", produces = "application/json; charset=utf-8")
    public MyGsonView queryTopic(Integer pageNo, Integer pageSize, String topicName) {
        MyGsonView gsonView = createGsonView();
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            List<TopicBean> topicList = contendService.queryTopicList((pageNo - 1) * pageSize, pageSize, topicName);
            Long num = contendService.countTopicList(topicName);
            result.put("topicList", topicList);
            result.put("total", num);
            gsonView.addStaticAttribute(BaseContants.DATA, result);
        } catch (Exception e) {
            LOGGER.error("queryTopic  error", e);
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
        }
        return gsonView;
    }

    /**
     * 
     * 功能描述:新增修改话题 <br>
     * 〈功能详细描述〉
     *
     * @param model
     * @param topic
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/saveTopic.do", produces = "application/json; charset=utf-8")
    public MyGsonView saveTopic(Model model, TopicBean topic, Principal principal) {
        model.addAttribute("topicBean", null);
        MyGsonView gsonView = createGsonView();
        try {
            topic.setCreator(principal.getName());
            contendService.saveTopic(topic);
            gsonView.addStaticAttribute(BaseContants.DATA, "");
        } catch (Exception e) {
            LOGGER.error("queryTopic  error", e);
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
        }
        return gsonView;
    }

    /**
     * 
     * 功能描述:上传图片 <br>
     * 〈功能详细描述〉
     *
     * @param multipartRequest
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/uploadMisc.do", produces = "application/json;charset=utf-8")
    @ResponseBody
    public MyGsonView uploadMisc(MultipartRequest multipartRequest) {
        MyGsonView gsonView = createGsonView();
        MultipartFile imageFile = multipartRequest.getFile("image");
        if (null != imageFile && !imageFile.isEmpty() && null != imageFile.getContentType()) {
            MediaType mediaType = MediaType.parseMediaType(imageFile.getContentType());
            List<MediaType> supports = MediaType.parseMediaTypes("image/*");
            for (MediaType support : supports) {
                if (support.includes(mediaType)) {
                    String imgUrl;
                    InputStream in = null;
                    try {
                        in = imageFile.getInputStream();
                        imgUrl = uimgStore
                                .onlyUpload(UIMGStore.FileType.MISC, mediaType.getSubtype().toLowerCase(), in);
                        gsonView.addStaticAttribute(BaseContants.DATA, imgUrl);
                    } catch (ImageServiceException e) {
                        LOGGER.error("UMIG服务异常", e);
                        setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
                    } catch (IOException ex) {
                        LOGGER.error("UMIG服务异常", ex);
                        setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
                    } finally {
                        IOUtils.closeQuietly(in);
                    }
                    break;
                }
                setErrorMsg(gsonView, ErrorCodeConstants.ERR_0001);
            }
        } else {
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0001);
        }
        return gsonView;
    }

    /**
     * 
     * 功能描述:删除话题 <br>
     * 〈功能详细描述〉
     *
     * @param topicId
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/delTopic.do", produces = "application/json; charset=utf-8")
    public MyGsonView delTopic(String topicId) {
        MyGsonView gsonView = createGsonView();
        try {
            contendService.deleteTopic(topicId);
            gsonView.addStaticAttribute(BaseContants.DATA, "");
        } catch (Exception e) {
            LOGGER.error("delTopic  error", e);
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
        }
        return gsonView;
    }

    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param start
     * @param limit
     * @param topicName
     * @param commContent
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/queryCommList.do", produces = "application/json; charset=utf-8")
    public MyGsonView queryCommList(Integer pageNo, Integer pageSize, String topicName, String commContent) {
        MyGsonView gsonView = createGsonView();
        try {
            RecordList<CommPersonDTO> backCommList = contendService.queryBackCommList((pageNo - 1) * pageSize,
                    pageSize, topicName, commContent);
            gsonView.addStaticAttribute(BaseContants.DATA, backCommList);
        } catch (Exception e) {
            LOGGER.error("queryCommList  error", e);
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
        }
        return gsonView;
    }

    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param start
     * @param limit
     * @param topicName
     * @param commContent
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/toBeBest.do", produces = "application/json; charset=utf-8")
    public MyGsonView queryCommList(Model model, Long commId, boolean isBest, PersonBean person) {
        model.addAttribute("personBean", null);
        MyGsonView gsonView = createGsonView();
        try {
            contendService.toBeBest(commId, isBest);
            contendService.modifyUserInfo(person);
            gsonView.addStaticAttribute(BaseContants.DATA, "");
        } catch (Exception e) {
            LOGGER.error("queryCommList  error", e);
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
        }
        return gsonView;
    }

    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param commId
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/delComm.do", produces = "application/json; charset=utf-8")
    public MyGsonView delComm(String commId) {
        MyGsonView gsonView = createGsonView();
        try {
            contendService.delComm(commId, null);
            gsonView.addStaticAttribute(BaseContants.DATA, "");
        } catch (Exception e) {
            LOGGER.error("delTopic  error", e);
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
        }
        return gsonView;
    }

}
